//
//  NSString+THCommon.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//

#import "NSString+THCommon.h"
@implementation NSString (THCommon)
static NSString *generateUdid = nil;

- (BOOL)zh_isTrue
{
    if ([self isEqualToString:@"True"]) {
        return YES;
    }else{
        return NO;
    }
}

- (BOOL)isNoEmpty {
    if ([THBaseUtil isBlankString:self]) {
        return NO;
    }else{
        return YES;
    }
}

+ (NSString*)generateUdid{
    if (generateUdid.length > 0) {
        return generateUdid;
    }
    
    CFUUIDRef puuid = CFUUIDCreate(nil);
    CFStringRef uuidString = CFUUIDCreateString(nil, puuid);
    NSString *uuid = (NSString *)CFBridgingRelease(CFStringCreateCopy(NULL, uuidString));
    CFRelease(puuid);
    CFRelease(uuidString);
    if (!uuid) {
        return @"";
    }
    generateUdid = [uuid stringByReplacingOccurrencesOfString:@"-" withString:@""];
    return generateUdid;
}

+ (NSMutableDictionary *)paramDictFromURL:(NSString *)url
{
    return [self paramDictFromURL:url urlDecode:NO];
}

+ (NSMutableDictionary *)paramDictFromURL:(NSString *)url urlDecode:(BOOL)urlDecode
{
    NSArray<NSString *> * queryList = [url componentsSeparatedByString:@"?"];
    if (queryList.count <= 2)
    {
        NSString * query = [queryList lastObject];
        NSArray * components = [query componentsSeparatedByString:@"&"];
        NSMutableDictionary * params = [NSMutableDictionary new];
        for (NSString * component in components)
        {
            if (component.length > 0 && [component containsString:@"="])
            {
                NSRange range = [component rangeOfString:@"="];
                NSString * key = [component substringToIndex:range.location];
                NSString * value = [component substringFromIndex:range.location + 1];
                if (urlDecode)
                {
                    value = [value stringByRemovingPercentEncoding];
                }
                params[key] = value;
            }
        }
        return params;
    }
    else
    {
        NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@"[^&\?]+=[^&\?]+" options:0 error:nil];
        NSArray<NSTextCheckingResult *> * matchList = [regex matchesInString:url options:0 range:NSMakeRange(0, url.length)];
        NSMutableDictionary * params = [NSMutableDictionary new];
        for (NSTextCheckingResult * match in matchList)
        {
            NSString * component = [url substringWithRange:match.range];
            NSRange range = [component rangeOfString:@"="];
            NSString * key = [component substringToIndex:range.location];
            NSString * value = [component substringFromIndex:range.location + 1];
            if (urlDecode)
            {
                value = [value stringByRemovingPercentEncoding];
            }
            params[key] = value;
        }
        return params;
    }
}

- (NSURL *)kURL
{
    if (self.length > 0)
    {
        NSURL * url = [NSURL URLWithString:self];
        if (url == nil)
        {
            NSString * encodeString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)self, (__bridge CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL, CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
            url = [NSURL URLWithString:encodeString];
        }
        return url;
    }
    return nil;
}

- (NSString*)hqFliterBlankAndEnter
{
    NSString *contetnA = [self stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    contetnA = [contetnA stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    contetnA = [contetnA stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    contetnA = [contetnA stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    return contetnA;
}

- (NSString *)subStringFrom:(NSString *)startString to:(NSString *)endString
{
    NSRange startRange = [self rangeOfString:startString];
    NSRange endRange = [self rangeOfString:endString];
    NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
    return [self substringWithRange:range];
}

- (CGSize)zh_imageUrlSize
{
    if (self.length <= 0) {
        return CGSizeZero;
    }
    NSDictionary *dict = [self.class paramDictFromURL:self];
    CGFloat height = [dict[@"h"] floatValue];
    CGFloat width  = [dict[@"w"] floatValue];
    return CGSizeMake(width, height);
}

//计算头像框宽度
- (CGFloat)zh_calImageWidth:(CGFloat)height;
{
    CGSize size = [self zh_imageUrlSize];
    CGFloat width = size.width/(isnan(size.height)?1:size.height) * height;
    if (isnan(width)) {
        return 0;
    }
    return width;
}

- (NSData *)base64Decode
{
//    return [GTMBase64 decodeString:self];
//    return [[GTMStringEncoding rfc4648Base64StringEncoding] decode:base64String];
    return [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
}
- (BOOL)lcck_isSpace{
    NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
    if ([[self stringByTrimmingCharactersInSet: set] length] == 0) {
        return YES;
    }
    return NO;
}

+(NSString *)countNumAndChangeformat:(NSString *)num
{
    int count = 0;
    long long int a = num.longLongValue;
    while (a != 0)
    {
        count++;
        a /= 10;
    }
    NSMutableString *string = [NSMutableString stringWithString:num];
    NSMutableString *newstring = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *str = [string substringWithRange:rang];
        [newstring insertString:str atIndex:0];
        [newstring insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];
    }
    [newstring insertString:string atIndex:0];
    return newstring;
}

- (NSInteger)countOccurencesOfString:(NSString*)searchString
{

    NSInteger strCount = [self length] - [[self stringByReplacingOccurrencesOfString:searchString withString:@""] length];

    return strCount / [searchString length];

}


- (NSString*)appendTimeUrl
{
    NSString *resultStr = self;
    if (![self containsString:@"?"] || ![self containsString:@"_t="]) {
        resultStr = [self stringByAppendingFormat:@"%@_t=%ld",[self containsString:@"?"]?@"&":@"?",(long)[[NSDate date] timeIntervalSince1970]];
    }

    return resultStr;
}

// 当文件名为中文时，解决url编码问题
- (NSString *)URLDecodedString
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)self, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

+ (NSString *)WhitePoint{
    
    return [NSString stringWithFormat:@"%@%@",@"Red",@"Packet"];
}
+ (NSString *)SmallWhitePoint:(NSString *)str {
    return [NSString stringWithFormat:@"%@%@%@",@"red",@"Packet",str];

}
+ (NSString *)AllSmallWhitePoint:(NSString *)str {
    return [NSString stringWithFormat:@"%@%@%@",@"red",@"packet",str];

}
+ (NSString *)WhitePointCh:(NSString *)prefix suffix:(NSString *)suffix{
    
    return [NSString stringWithFormat:@"%@%@%@%@",prefix,@"红",@"包",suffix];
}

+ (NSString *)Vguest:(NSString *)prefix suffix:(NSString *)suffix{
    return [NSString stringWithFormat:@"%@%@%@%@",prefix,@"V",@"ip",suffix];
}
+ (NSString *)SmallVguest:(NSString *)str {
    return [NSString stringWithFormat:@"%@%@%@",@"v",@"ip",str];
}
+ (NSString *)BigllVguest:(NSString *)prefix suffix:(NSString *)suffix{
    return [NSString stringWithFormat:@"%@%@%@%@",prefix,@"V",@"IP",suffix];
}

+ (NSString *)jinbiCh:(NSString *)prefix suffix:(NSString *)suffix{
    return [NSString stringWithFormat:@"%@%@%@%@",prefix,@"金",@"币",suffix];
}

+ (NSString *)RecFunApiChange:(NSString *)str{
    NSString *newStr = [NSString stringWithFormat:@"%@%@",@"rech",@"arge"];
    return  [str stringByReplacingOccurrencesOfString:@"RecFun" withString:newStr];
}
@end
